import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:learning/bean/result_entity.dart';
import 'package:learning/generated/l10n.dart';

class Request {
  static String baseUrl = "http://192.168.1.6:8085/api/";

  static Future<ResultEntity> get(String url) async {
    try {
      ResultEntity base = await Request.base(url, "GET", null);
      // print(base);
      if (base.success) {
        return base;
      } else {
        throw Exception(base);
        //  return ResultEntity(success: true, msg: 'Error');
      }
    } catch (e) {
      print(e);
      return ResultEntity();
    }
  }

  static Map<String, String> getHeader() {
    var lang = S.current.locale;
    print("Lang Demo1: $lang");
    Map<String, String> map = <String, String>{
      "Content-Type": "application/json",
      "Accept": "application/json",
      "terminal": "3",
      "token": "12345678901234567890123",
      "language": lang,
    };

    return map;
  }

  static FutureOr<ResultEntity> post(
      String url, Map<String, dynamic> data) async {
    ResultEntity base = await Request.base(url, "POST", data);

    return base;
  }

  static Future<ResultEntity> base(
      String url, String method, Map<String, dynamic>? data) async {
    try {
      var uri = Uri.parse(baseUrl + url);
      http.Request request = http.Request(method, uri);
      request.headers.addAll(getHeader());
      if (data != null) {
        request.body = jsonEncode(data);
      }
      http.Client client = http.Client();
      final response = await client.send(request);
      if (response.statusCode == 200) {
        Stream<String> stringStream = response.stream.transform(utf8.decoder);

        // 将字符串流转换为单一字符串
        String responseBody = await stringStream.join();
        //  print(responseBody);
        Map<String, dynamic> data = jsonDecode(responseBody);
        print(data);
        //  print(Result.fromJson(data).data);
        return ResultEntity.fromJson(data);
      } else {
        throw Exception('Failed!');
      }
    } catch (e) {
      print(e);
      rethrow; // 如果需要将错误继续传递给调用者
    }
  }

  static bool isList(Object object) {
    return object is List;
  }
}
